package com.lhy.framework.beans.factory.support;

import com.lhy.framework.beans.BeansException;
import com.lhy.framework.beans.factory.factory.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @ClassName JdkInstantiationStrategy
 * @Description JDK 方式创建对象
 * @Author lihaiyang
 * @Date 2022/9/8 23:25
 * @Version 1.0
 */
public class JdkInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantitate(String beanName, BeanDefinition beanDefinition, Constructor constructor, Object[] args) throws BeansException {
        Class clazz = beanDefinition.getClazz();
        try {
            if (null != constructor) {
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
            throw new BeansException("Failed to instantiate[" + clazz.getName() + "]", e);
        }
    }
}
